const { codeToMessage } = require("./message");
const zlib = require("zlib");
const koaReq = require("request");
const http = require("http");
const fs = require("fs");
//const store = require("../../store/index");
const successFormat = (code, data) => {
  return {
    status: 1,
    data: data,
    message: codeToMessage(code),
    code: code,
  };
};
const errorFormat = (code, data) => {
  return {
    status: 0,
    data: data || [],
    message: codeToMessage(code),
    code: code,
  };
};
const buildResponse = (req, data) => {
  var acceptEncoding = req.headers["accept-encoding"];
  if (acceptEncoding.indexOf("gzip") != -1) {
    return zlib.gzipSync(JSON.stringify(data));
  } else {
    return JSON.stringify(data);
  }
};
const Get = (url, data) => {
  return new Promise((resolve, reject) => {
    koaReq(
      {
        url: url,
        method: "get",
        qs: data,
        json: true, //设置返回的数据为json
      },
      (err, res, body) => {
        if (!err && res.status == 1) {
          resolve(body);
        } else {
          reject(err);
        }
      }
    );
  });
};
const Post = (url, data) => {
  return new Promise((resolve, reject) => {
    koaReq(
      {
        url: url,
        method: "post",
        form: data,
        json: true, //设置返回的数据为json
      },
      (err, res, body) => {
        if (!err && res.status == 1) {
          resolve(body);
        } else {
          reject(err);
        }
      }
    );
  });
};

const Put = (url, data) => {
  return new Promise((resolve, reject) => {
    koaReq(
      {
        url: url,
        method: "put",
        form: data,
        json: true, //设置返回的数据为json
      },
      (err, res, body) => {
        if (!err && res.status == 1) {
          resolve(body);
        } else {
          reject(err);
        }
      }
    );
  });
};
const Delete = (url, data) => {
  return new Promise((resolve, reject) => {
    koaReq(
      {
        url: url,
        method: "delete",
        form: data,
        json: true, //设置返回的数据为json
      },
      (err, res, body) => {
        if (!err && res.status == 1) {
          resolve(body);
        } else {
          reject(err);
        }
      }
    );
  });
};

const fetchImage = (url) => {
  return new Promise((resolve, reject) => {
    const fileName = /.+\/((.+)\.(png|jpg|jpeg|gif))$/.exec(url);
    fileName
      ? http
          .get(url, (response) => {
            //data 存储图片数据，是二进制流
            var data = "";
            // 一定要设置encode，否则即使在pic/downImg/中有1.jpg,也是无法显示的
            response.setEncoding("binary");
            // 当数据到达时会触发data事件
            response.on("data", function (chunk) {
              data += chunk;
            });
            // 当数据接收完毕之后，会触发end事件
            response.on("end", function () {
              //resolve(data);
              //写入文件
              fs.writeFile(
                "./temp/images/from/" + fileName[1],
                data,
                "binary",
                (err) => {
                  if (err) {
                    console.log(err);
                    reject({ err: { message: "write error" } });
                  } else {
                    resolve({
                      url: "./temp/images/from/" + fileName[1],
                      name: fileName[2],
                      ext: fileName[3],
                    });
                  }
                }
              );
            });
          })
          .on("error", function (err) {
            console.log(err);
            reject(err);
          })
      : reject({ err: { message: "write error" } });
  });
};

module.exports = {
  successFormat,
  errorFormat,
  buildResponse,
  Get,
  Post,
  Put,
  Delete,
  fetchImage,
};
